package cn.jdemo.juc.future.wrapper;

/**
 * 任务获取，则wait等待通知
 * @see Object#wait()
 * @see Object#notify()
 */
public class MyFutureImpl<R> implements MyFuture<R> {

    private R result;

    private boolean isDone;

    private Object LOCK = new Object();

    @Override
    public R get() throws InterruptedException {
        synchronized (LOCK){
            while(!isDone){
                LOCK.wait();
            }
        }
        return result;
    }

    @Override
    public boolean done() {
        return isDone;
    }

    /**
     * finish 方法用于设置任务执行结果
     *
     * @param result
     */
    public void finish(R result) {
        // 多线程下，需要加锁
        synchronized (LOCK) {
            if (isDone) {
                return;
            }
            // 完成那就设置结果，并更新isDone为true
            this.result = result;
            this.isDone = true;
            // 可能等待获取结果的线程，需要唤醒这些线程
            LOCK.notifyAll();
        }
    }
}
